package com.jyh.service.basicBi;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.ModelAndView;

import com.github.pagehelper.PageHelper;
import com.jyh.config.BaseAction;
import com.jyh.config.datasource.TargetDataSource;
import com.jyh.db.dao.BiDataStatisticsDao;
import com.jyh.db.dao.ChannelDao;
import com.jyh.db.entity.JyhChannelList;
import com.jyh.db.entity.JyhChannelListExample;
import com.jyh.db.mapper.JyhChannelListMapper;
import com.jyh.dbOrder.dao.LoanDao;
import com.jyh.util.Utils;

@Service
public class StatistService extends BaseAction {
	@Autowired
	private LoanDao loanDao;
	@Autowired
	private BiDataStatisticsDao statisticsDao;
	@Autowired
	private ChannelDao channelDao;


	@TargetDataSource(name = "user")
	public ModelAndView getStatistList(String page) {
		ModelAndView mv = new ModelAndView("statisticsBi/channelStatistics");
		int lineSize = 20; // 每页显示记录20条数
		int pageCount = 0; // 总页数
		int count = 0; // 数据总数
		int currentPage = 1; // 当前是第几页,默认是第一页
		if (page == null || "1".equals(page)) {
		} else {
			currentPage = Integer.parseInt(page); // 当前是第几页,默认是第一页
		}
		if (currentPage < 1) {
			currentPage = 1;
		}
		
		String sql = "select t1.deviceType,t1.channelNumber,t1.userNumber,t1.userName,t1.logtime,COUNT(t2.userNO)loanSumNo,t3.countCreditNum,t3.sumCreditMoney,"
				+ "t4.countOverdueNum,t5.sumRefundMoney from credit_user.jyh_person as t1 LEFT JOIN credit_order.jyh_order as t2 ON t1.userNumber = t2.userNO  "
				+ "LEFT JOIN (select a1.userNO,COUNT(a1.userNO)countCreditNum,SUM(a2.putMoney)sumCreditMoney from credit_order.jyh_order as a1 "
				+ "INNER JOIN credit_order.jyh_order_payment as a2 on a1.orderNO=a2.orderNO GROUP BY a1.userNO) as t3 on t1.userNumber = t3.userNo "
				+ "LEFT JOIN(select a1.userNO,COUNT(a1.userNO)countOverdueNum from credit_order.jyh_order as a1 INNER JOIN credit_order.jyh_order_payment as a2 "
				+ "on a1.orderNO=a2.orderNO where a2.isOverdue=1  GROUP BY a1.userNO ) as t4 ON t1.userNumber=t4.userNO "
				+ "LEFT JOIN (select a1.userNO,SUM(a2.putMoney)sumRefundMoney from credit_order.jyh_order as a1 INNER JOIN credit_order.jyh_order_payment as a2 "
				+ "on a1.orderNO=a2.orderNO where a2.isRepay=2  GROUP BY a1.userNO) as t5 on t1.userNumber=t5.userNO GROUP BY t1.userNumber order by t1.logtime desc";

		List<Map<String, Object>> userList = loanDao.getList(sql + limit(currentPage, lineSize));
		
		Map<String,String> channelMap = channelDao.getChannel();
		
		List<Map<String, Object>> userLists = loanDao.getList(sql);
		count = userLists.size();
		int temp = count / lineSize; // 取商
		int tem2 = count % lineSize;// 取余数
		if (tem2 > 0 && tem2 < lineSize && temp > 0) {
			pageCount = count / lineSize + 1; // 总页数
		} else if (tem2 == 0 && temp > 0) {
			pageCount = temp;
		} else {
			pageCount = 1; // 总页数
		}
		if (currentPage >= pageCount) {
			currentPage = pageCount;
		}

		List<Map<String, String>> list = new ArrayList<Map<String, String>>();
		PageHelper.startPage(1, 1);// 只对第一个查询有效
		for (int i = 0; i < userList.size(); i++) {
			Map<String, String> map = new HashMap<String, String>();
			/* 注册来源 */
			String deviceType = userList.get(i).get("deviceType") + "";
			// 0:SDK-android 1:SDK-ios 2:WEB 3：WAP
			if ("0".equals(deviceType)) {
				map.put("deviceType", "SDK-android");
			} else if ("1".equals(deviceType)) {
				map.put("deviceType", "SDK-ios");
			} else if ("2".equals(deviceType)) {
				map.put("deviceType", "WEB");
			} else if ("3".equals(deviceType)) {
				map.put("deviceType", "WAP");
			} else {
				map.put("deviceType", "未知");
			}
			String channelNumber = userList.get(i).get("channelNumber") + "";
			map.put("channelNumber",channelMap.get(channelNumber));

			/* 用户ID */
			String userNo = userList.get(i).get("userNumber") + "";
			map.put("userNo", userNo);

			/* 用户名称 */
			String userName = userList.get(i).get("userName") + "";
			if (Utils.isNull(userName)) {
				map.put("userName", "-");
			} else {
				map.put("userName", userName);
			}
			/* 注册时间 */
			String logtime = userList.get(i).get("logtime") + "";
			map.put("logtime", logtime);
			/* 借款次数 */
			String loanSumNo = Utils.getStrforIn(userList.get(i).get("loanSumNo") + "");
			if (Integer.parseInt(loanSumNo) > 0) {
				map.put("isLoan", "是");
			} else {
				map.put("isLoan", "否");
			}
			map.put("loanSumNo", loanSumNo);
			/* 放款次数 */
			String countCreditNum = Utils.getStrforIn(userList.get(i).get("countCreditNum") + "");
			if (Integer.parseInt(countCreditNum) > 0) {
				map.put("isCredit", "是");
			} else {
				map.put("isCredit", "否");
			}
			map.put("countCreditNum", countCreditNum);
			/* 放款金额 */
			String sumCreditMoney = Utils.getStrforIn(userList.get(i).get("sumCreditMoney") + "");
			map.put("sumCreditMoney", sumCreditMoney);
			/* 逾期次数 */
			String countOverdueNum = Utils.getStrforIn(userList.get(i).get("countOverdueNum") + "");
			if (Integer.parseInt(countOverdueNum) > 0) {
				map.put("isOverdue", "是");
			} else {
				map.put("isOverdue", "否");
			}
			map.put("countOverdueNum", countOverdueNum);

			/* 累计借款金额 */
			String sumRefundMoney = Utils.getStrforIn(userList.get(i).get("sumRefundMoney") + "");
			map.put("sumRefundMoney", sumRefundMoney);
			list.add(map);
		}
		mv.addObject("list", list);
		mv.addObject("pageCount", pageCount);
		mv.addObject("currentPage", currentPage);
		mv.addObject("count", count);
		return mv;
	}

	public ModelAndView getAnalysis(String time) {
		ModelAndView mv = new ModelAndView("statisticsBi/dataAnalysis");
		if(Utils.isNull(time)){
			return mv;
		}
		// 借款笔数
		String loanSum = Utils.getStrforIn(statisticsDao.getFrequencyBorrowing(time));
		// 总逾期笔数
		Map<String, Object> map1 = statisticsDao.getOverdueData(time);
		String overdueNum = Utils.getStrforIn(map1.get("countId") + "");

		String oveTime = getTime(time, 14);
		List<Map<String, String>> listReturn = new ArrayList<Map<String, String>>();
		for (int i = 0; i < 90; i++) {
			String overdueTeime = getTime(oveTime, i);
			Map<String, String> maps = new HashMap<String, String>();
			maps.put("time", overdueTeime);
			maps.put("loanSum", loanSum);
			// 当天剩余逾期笔数
			String overdueSum = Utils.getStrforIn(statisticsDao.getOnDayOrderOverdue(time, overdueTeime));
			maps.put("overdueSum", overdueSum);
			// 逾期率
			maps.put("overdueRate", Utils.getMathematicsTo100(overdueSum, loanSum));
			// 催回笔数
			String pushBack = Utils.getStrforIn(statisticsDao.getPushBack(time, overdueTeime));
			maps.put("pushBack", pushBack);
			// 催回率
			maps.put("pushBackRate", Utils.getMathematicsTo100(pushBack, overdueNum));
			listReturn.add(maps);
		}
		mv.addObject("list", listReturn);
		mv.addObject("time", time);
		return mv;
	}
	
	

	/**
	 * 获取向后多长时间
	 * 
	 * @param time
	 * @param i
	 * @return
	 */
	private static String getTime(String time, int i) {
		Date beginDate = null;
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
		String etime = "";
		try {
			beginDate = formatter.parse(time);
			Calendar date = Calendar.getInstance();
			date.setTime(beginDate);
			date.set(Calendar.DATE, date.get(Calendar.DATE) + i);
			Date endDate = formatter.parse(formatter.format(date.getTime()));
			etime = formatter.format(endDate);
		} catch (java.text.ParseException e) {
			e.printStackTrace();
		}
		return etime;
	}
}
